const express = require('express')
const router = express.Router()
const articals = require('../models/artical')
const jwt = require('jsonwebtoken')

// 获取文章列表
router.get('/artical', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    const query = articals.find({
      author: decode.username
    })
    const page = req.query.pagenum
    const rows = 10
    query.skip((page - 1) * rows);
    query.limit(rows);
    query.exec((err, rs) => {
      if (err) {
        res.send(err);
      } else {
        //计算数据总数
        articals.find({
          author: decode.username
        }, (err, result) => {
          res.send({
            status: 200,
            data: rs,
            total: result.length
          })
        })
      }
    })
  })
})

// 添加文章
router.post('/artical/new', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    req.body.author = decode.username
    new articals(req.body).save(err => {
      if (err) return res.status(500).send({
          message: '添加文章失败',
          status: 500
        })
      res.send({
        message: '添加文章成功',
        status: 200
      })
    })
  })
})

// 编辑修改文章
router.post('/artical', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    articals.findByIdAndUpdate(req.body.id, {
      title: req.body.title,
      content: req.body.content
    }, err => {
      if (err) return res.status(500).send('Server Error')
      res.send({
        message: '修改文章成功',
        status: 200
      })
    })
  })
})

// 删除文章数据（一条）
router.delete('/artical', (req, res) => {
  let token = req.get('Authorization')
  jwt.verify(token, 'abc', (err, decode) => {
    if (err) return res.send({code: 0, message: "token已失效"})
    articals.findByIdAndRemove(req.query.id, err => {
      if (err) return res.status(500).send('Server Error')
      res.send({
        message: '删除文章成功',
        status: 200
      })
    })
  })
})

module.exports = router
